package com.longkier.gx_library_springboot.Service;

import com.longkier.gx_library_springboot.entity.BookType;
import com.longkier.gx_library_springboot.exception.CustomException;
import com.longkier.gx_library_springboot.repository.BookRepository;
import com.longkier.gx_library_springboot.repository.BookTypeRepository;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@RequiredArgsConstructor
public class BookTypeService {

    private final BookTypeRepository bookTypeRepository;
    private final BookRepository bookRepository;

    // 获取所有借阅类别
    public List<BookType> getAllBookTypes() {
        return bookTypeRepository.findAll();
    }

    // 根据ID获取借阅类别
    public Optional<BookType> getBookTypeById(Long id) {
        return bookTypeRepository.findById(id);
    }

    // 保存或更新借阅类别
    public BookType saveOrUpdateBookType(@NotNull BookType bookType) {
        if (bookType.getTypeId() == null) {
            bookType.setCreateTime(LocalDateTime.now());
        }
        bookType.setUpdateTime(LocalDateTime.now());
        return bookTypeRepository.save(bookType);
    }

    // 删除借阅类别
    public void deleteBookType(Long id) {
        @NotNull Optional<BookType> bookTypeOptional = bookTypeRepository.findById(id);
        bookTypeOptional.ifPresent(bookType -> {
            String typeName = bookType.getTypeName();
            if (!bookRepository.existsByBookType(typeName)) {
                bookTypeRepository.deleteById(id);
            } else {
                throw new CustomException(500,"该借阅类别下有图书，无法删除");
            }
        });
        if (bookTypeOptional.isEmpty()) {
            throw new CustomException(500,"未找到该借阅类别");
        }
    }
}
